package com.liuqianfei.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式工具
 * @author liuqianfei
 * @since 2016-06-14
 */
public class RegExpUtil
{

    /**
     * 查找给定字符串中是否有匹配给定正则的段
     * @param regexp 正则表达式
     * @param src 字符串
     * @return 存在匹配返回 true，否则返回 false
     */
    public static boolean match(String regexp, String src, boolean caseInsensitive)
    {
        if ((regexp == null) || (regexp.length() == 0) || (src == null) || (src.length() == 0))
        {
            return false;
        }

        Pattern localPattern;
        if (caseInsensitive)
            localPattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
        else
            localPattern = Pattern.compile(regexp);

        Matcher localMatcher = localPattern.matcher(src);

        return localMatcher.find();
    }

    // 获取分组
    public static String group(String regexp, String src, boolean caseInsensitive, int group)
    {
        Pattern pattern;
        if (caseInsensitive)
            pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
        else
            pattern = Pattern.compile(regexp);

        Matcher matcher = pattern.matcher(src);
        if (matcher.find())
        {
            int groupCount = matcher.groupCount();
            if (groupCount < group)
                return null;
            return matcher.group(group);
        }
        else
        {
            return null;
        }
    }
}
